from django_redis import get_redis_connection
from drf_haystack.serializers import HaystackSerializer
from rest_framework import serializers

from goods.models import SKU
from goods.search_indexes import SKUIndex


class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = '__all__'


class SKUIndexSerializer(HaystackSerializer):
    """
    SKU索引结果数据序列化器
    """
    object = SKUSerializer(read_only=True)

    class Meta:
        index_classes = [SKUIndex]
        fields = ('text', 'object')

class AddUserBrowsingHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):

        try:
            SKU.objects.get(id=attrs['sku_id'])

        except:
            raise serializers.ValidationError('sku_id不存在')

        return attrs

    def create(self, validated_data):

        user = self.context['request'].user
        sku_id = validated_data['sku_id']

        # 建立连接
        conn = get_redis_connection('history')
        pl = conn.pipeline()

        # 判断一下sku_id是否存,存在则删除
        pl.lrem('history_%s' % user.id, 0, sku_id)

        # 写入数据
        pl.lpush('history_%s' % user.id, sku_id)

        # 控制数量
        pl.ltrim('history_%s' % user.id, 0, 4)

        pl.execute()

        return validated_data